﻿using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using UFIDA.U8.PUB;

namespace UFIDA.U8C.AnLian.NBBankSync
{
     

        public static class HttpHelper
        {
            public static string PostDataToServer(string ip, string js)
            {
                return PostHttpHelper.PostHttp(ip, js, "application/json", 30000);
            }

            public static string PostDataToServerform(string ip, string js)
            {
                return PostHttpHelper.PostHttp(ip, js, "application/x-www-form-urlencoded", 30000);
            }

            public static string PostDataToServerDic(string ip, Dictionary<string, string> dic, string contenttype)
            {
                return PostHttpHelper.PostHttp(ip, dic, contenttype);
            }

            public static string GetDataFromServerDic(string url, Dictionary<string, string> js, string token, string contenttype)
            {
                return PostHttpHelper.GetHttp(url, js, token, contenttype, 5000);
            }
        }
        


        public class PostHttpHelper
        {
            //body是要传递的参数,格式"roleId=1&uid=2"
            //post的cotentType填写:
            //"application/x-www-form-urlencoded"
            //soap填写:"text/xml; charset=utf-8"
            //timeout 填写超时毫秒
            public static string PostHttp(string url, string body, string contentType, int timeout)
            {
                string responseContent = String.Empty;
                //body = ConvertHelper.GetHtmlEncode(body);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
                try
                {


                    httpWebRequest.ContentType = contentType;
                    httpWebRequest.Method = "POST";
                    httpWebRequest.Timeout = timeout;
                    httpWebRequest.ServicePoint.Expect100Continue = false;
                    httpWebRequest.ServicePoint.ConnectionLimit = 500;
                U8.PUB.LogHelper.WriteLine("URL LOG", "LOG", url + body);
                    byte[] btBodys = Encoding.UTF8.GetBytes(body);
                    httpWebRequest.ContentLength = btBodys.Length;
                    httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);
                    using (HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse())
                    {


                        Stream responseStream = httpWebResponse.GetResponseStream();

                        if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                            responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                        else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                            responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                        Encoding encoding;
                        //if (httpWebResponse.CharacterSet.ToUpper().Contains("ISO-8859-1"))
                        //    encoding = System.Text.Encoding.GetEncoding("ISO-8859-1");
                        //else
                        encoding = Encoding.UTF8;
                        //encoding = Encoding.GetEncoding("GBK");
                        StreamReader streamReader;
                        streamReader = new StreamReader(responseStream, encoding, true);
                        String resultstr = streamReader.ReadToEnd();

                        resultstr = System.Web.HttpUtility.UrlDecode(resultstr);
                        responseContent = resultstr;

                        httpWebResponse.Close();
                        streamReader.Close();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    httpWebRequest.Abort();
                }


                return responseContent;
            }


            /// <summary>
            /// 指定Post地址使用Get 方式获取全部字符串
            /// </summary>
            /// <param name="url">请求后台地址</param>
            /// <returns></returns>
            public static string PostHttp(string url, Dictionary<string, string> dic, string contenttype)
            {
                string result = "";
                System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3
                                       | SecurityProtocolType.Tls
                                       | (SecurityProtocolType)0x300
                                       | (SecurityProtocolType)0xC00; 
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
                req.Method = "POST";
                req.ContentType = contenttype;
                #region 添加Post 参数
                StringBuilder builder = new StringBuilder();
                int i = 0;
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    i++;
                }

                U8.PUB.LogHelper.WriteLine("URL LOG", "LOG", url + builder.ToString());

                
                byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
                req.ContentLength = data.Length;
                using (Stream reqStream = req.GetRequestStream())
                {
                    reqStream.Write(data, 0, data.Length);
                    reqStream.Close();
                }
                #endregion
                HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
                Stream stream = resp.GetResponseStream();
                //获取响应内容
                using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
                {
                    result = reader.ReadToEnd();
                }
                return result;
            }


            public static string GetHttp(string url, Dictionary<string, string> dic, string token, string contentType, int timeout)
            {
                int i = 0;
                StringBuilder builder = new StringBuilder();
                foreach (var item in dic)
                {
                    if (i > 0)
                        builder.Append("&");
                    //if (item.Key.ToString() == "created_at" || item.Key.ToString() == "updated_at")
                    //{
                    //    builder.AppendFormat("{0}={1}", item.Key, Convert.ToDateTime(item.Value.ToString()));
                    //}
                    //else
                    //{
                    builder.AppendFormat("{0}={1}", item.Key, item.Value);
                    //}
                    i++;
                }

                U8.PUB.LogHelper.WriteLine("GET LOG", "LOG", url + builder.ToString());
                //body = ConvertHelper.GetHtmlEncode(body);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url + "" + builder.ToString());

               
                if (!string.IsNullOrEmpty(token))
	            {
                    httpWebRequest.Headers.Add("Authorization", token);
	            }
                httpWebRequest.Headers.Add("apikey", "web-user");
                

                httpWebRequest.ContentType = contentType;
                httpWebRequest.Method = "GET";
                httpWebRequest.Timeout = timeout;

                //byte[] btBodys = Encoding.UTF8.GetBytes(body);
                //httpWebRequest.ContentLength = btBodys.Length;
                //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                Stream responseStream = httpWebResponse.GetResponseStream();

                if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                    responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                String resultstr = streamReader.ReadToEnd();
                string responseContent = resultstr;
                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();

                return responseContent;
            }
            public static string GetHttp(string url, string body, string contentType, int timeout)
            {
                if (!string.IsNullOrEmpty(body))
                {
                    url = url + "" + body;
                }
                //body = ConvertHelper.GetHtmlEncode(body);
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);


                httpWebRequest.ContentType = contentType;
                httpWebRequest.Method = "GET";
                httpWebRequest.Timeout = timeout;

                //byte[] btBodys = Encoding.UTF8.GetBytes(body);
                //httpWebRequest.ContentLength = btBodys.Length;
                //httpWebRequest.GetRequestStream().Write(btBodys, 0, btBodys.Length);

                HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse();

                Stream responseStream = httpWebResponse.GetResponseStream();

                if (httpWebResponse.ContentEncoding.ToLower().Contains("gzip"))
                    responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
                else if (httpWebResponse.ContentEncoding.ToLower().Contains("deflate"))
                    responseStream = new DeflateStream(responseStream, CompressionMode.Decompress);
                StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
                String resultstr = streamReader.ReadToEnd();
                string responseContent = resultstr;
                httpWebResponse.Close();
                streamReader.Close();
                httpWebRequest.Abort();

                return responseContent;
            }
        }
     
}
